package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code24PalindromeLinkedList {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return false;
        }
        if (head.next == null) {
            return true;
        }
        // 快慢指针找到中间位置
        ListNode slow = head;
        ListNode fast = head;
        // slow 前一个位置, 逆序前半部分链表
        ListNode prepre = null;
        ListNode preSlow = null;
        while (fast != null && fast.next != null) {
            prepre = preSlow;
            preSlow = slow;

            slow = slow.next;
            fast = fast.next.next;

            preSlow.next = prepre;
        }

        // 奇数情况跳过正中间的节点
        if (fast != null) {
            slow = slow.next;
        }

        ListNode pp = null;
        ListNode p = slow;
        boolean isPalindrome = true;
        while (preSlow != null && slow != null) {
            if (preSlow.val != slow.val) {
                isPalindrome = false;
            }

            pp = p;
            p = preSlow;

            preSlow = preSlow.next;
            slow = slow.next;

            p.next = pp;
        }
        return isPalindrome;
    }
}
